package com.sense.kukoo.biz_library.view

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.sense.feel.common.utils.ToastUtils
import com.sense.kukoo.biz_library.R
import com.sense.kukoo.biz_library.adapter.FollowAdapter
import com.sense.kukoo.biz_library.databinding.BizLibraryFragmentLibraryBinding
import com.sense.kukoo.biz_library.vm.LibraryViewModel
import com.sense.kukoo.common.constant.ARouterUrl
import com.sense.kukoo.common.constant.ConstantConfig
import com.sense.kukoo.common.event.MainPageEvent
import com.sense.kukoo.common.listener.OnScrollYChangedListener
import com.sense.kukoo.common.media.Kukoo
import com.sense.kukoo.common.media.bean.LocalMediaListItemBean
import com.sense.kukoo.common.media.watcher.UserWatcher
import com.sense.kukoo.common.mvvm.view.BaseMvvmFragment
import com.sense.kukoo.common.repo.Repo
import com.sense.kukoo.common.repo.biz.FollowContentBean
import com.sense.kukoo.common.repo.http.bean.IndexContentBean
import com.sense.kukoo.common.repo.http.bean.UserSearchBean
import com.sense.kukoo.common.wiget.state.EmptyFollowPageState
import com.sense.kukoo.common.wiget.state.NetworkErrorState
import com.sense.kukoo.common.wiget.state.NotLoginState
import com.zy.multistatepage.state.SuccessState
import org.greenrobot.eventbus.EventBus

class LibraryFragment : BaseMvvmFragment<LibraryViewModel, BizLibraryFragmentLibraryBinding>() {

    private val TAG: String = javaClass.simpleName
    private lateinit var mAdapter: FollowAdapter

    private var mOnScrollYChangedListener: OnScrollYChangedListener? = null
    private var mCurrentState:Int = ConstantConfig.STATE_SUCCESS
    private var mFlagToRefresh = true

    var mCurrentMusic: LocalMediaListItemBean? = null
    var mCurrentPlayState: Int = UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING

    companion object {
        @JvmStatic
        fun newInstance() = LibraryFragment()
    }

    override fun getLayout(): Int = R.layout.biz_library_fragment_library

    override fun getViewModelClass(): Class<LibraryViewModel> = LibraryViewModel::class.java

    override fun initParam() {}

    override fun responseVM(action: Int) {}

    override fun initData() {
        mBinding.lifecycleOwner = this
        mBinding.vm = mViewModel
        //
        bindAction(mViewModel.action_finishRefresh){
            mBinding.refreshLayout.finishRefresh()
        }
        bindAction(mViewModel.action_finishLoadMore){
            mBinding.refreshLayout.finishLoadMore()
        }
        bindAction(mViewModel.action_network_error){
            refreshState(ConstantConfig.STATE_NETWORK_ERROR)
        }
        bindAction(mViewModel.action_toChannelPage){
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_CHANNEL_ACTIVITY)
                .withString(ARouterUrl.KEY_FROM, "${it.id}")
                .navigation()
        }
        bindData(mViewModel.data_content){
            if(it.size == 0){
                refreshState(ConstantConfig.STATE_EMPTY_LIST)
            } else {
                refreshState(ConstantConfig.STATE_SUCCESS)
                mAdapter.list = it
                mAdapter.notifyDataSetChanged()
            }
        }
        bindData(mViewModel.data_enableLoadMore){
            mBinding.refreshLayout.setEnableLoadMore(it)
        }
    }

    override fun initView() {
        mAdapter = FollowAdapter(mutableListOf(), mListener)
        mBinding.recyclerView.adapter = mAdapter

        val linearLayoutManager = LinearLayoutManager(context)
        mBinding.recyclerView.layoutManager = linearLayoutManager
        mBinding.refreshLayout.setOnRefreshListener {
            //OnRefresh
            mViewModel.refreshFollowContents()
        }
        mBinding.refreshLayout.setOnLoadMoreListener {
            //OnLoadMore
            mViewModel.loadMoreFollowContents()
        }
        //
        mBinding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {

            private var isScroll = false

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                if (isScroll) {
                    mOnScrollYChangedListener?.onChanged(1, 0, dy, RecyclerView.SCROLL_STATE_DRAGGING)
                }
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                //LoggerManager.e(TAG, "onScrollStateChanged newState=${newState}")
                if(newState == RecyclerView.SCROLL_STATE_IDLE){
                    isScroll = false
                    mOnScrollYChangedListener?.onChanged(1, 0, 0, RecyclerView.SCROLL_STATE_IDLE)
                } else {
                    isScroll = true
                }
            }
        })
    }

    override fun singleLazyLoad() {}

    override fun onResume() {
        super.onResume()
        //
        val state = mBinding.multiStateContainer.currentState
        if(!Repo.login.isLogin()){
            if(!(state is NotLoginState)){
                refreshState(ConstantConfig.STATE_NOT_LOGIN)
            }
            return
        }
        //
        if(state is NotLoginState){
            refreshState(ConstantConfig.STATE_SUCCESS)
            mBinding.refreshLayout.autoRefresh()
            return
        }
        val isSuccess = state == null || state is SuccessState
        if (isSuccess) {
            if (mFlagToRefresh) {
                mFlagToRefresh = false
                mBinding.refreshLayout.autoRefresh()
            }
            return
        }
        if(state is EmptyFollowPageState){
            mViewModel.refreshFollowContents()
        } else if(state is NetworkErrorState){
            mViewModel.retryLastCall()
        }
    }

    fun setOnScrollYChangedListener(l: OnScrollYChangedListener){
        mOnScrollYChangedListener = l
    }

    private val mListener = object :FollowAdapter.FollowContentEventListener{
        override fun onItemClick(data: IndexContentBean) {
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_DESCRIPTION_ACTIVITY)
                .withString(ARouterUrl.KEY_FROM, "${data.id}")
                .navigation()
        }

        override fun onChannelClick(data: IndexContentBean) {
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_CHANNEL_ACTIVITY)
                .withString(ARouterUrl.KEY_FROM, "${data.userId}")
                .navigation()
        }

        override fun onBtnPlayClick(data: IndexContentBean) {
            if(mCurrentMusic?.idOfChapter() == data.id){
                //当前的
                when (mCurrentPlayState) {
                    UserWatcher.MusicStateWatcher.STATE_ERROR_RETRYING,
                    UserWatcher.MusicStateWatcher.STATE_SEEKING,
                    UserWatcher.MusicStateWatcher.STATE_PREPARE,
                    UserWatcher.MusicStateWatcher.STATE_PLAYING -> {
                        Kukoo.input.pause()
                    }
                    /*UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING ->{}
                    UserWatcher.MusicStateWatcher.STATE_PAUSE ->{}*/
                    else -> {
                        Kukoo.input.start()
                    }
                }
            }else{
                //非当前的
                Kukoo.input.play(LocalMediaListItemBean(data))
            }
        }

        override fun onTitleChannelClick(data: FollowContentBean) {
            val user: UserSearchBean = data.currentSelectedUser!!
            mViewModel.onTitleChannelClick(user)
        }

        override fun onTitleItemClick(user: UserSearchBean) {
            mViewModel.onTitleItemClick(user)
        }
    }

    private fun refreshState(state:Int){
        if(mCurrentState == state){
            return
        }
        mCurrentState = state
        when (state) {
            ConstantConfig.STATE_SUCCESS -> {
                mBinding.multiStateContainer.show<SuccessState>()
            }
            ConstantConfig.STATE_NOT_LOGIN -> {
                mBinding.multiStateContainer.show<NotLoginState> {
                    it.onClick {
                        ARouter.getInstance()
                            .build(ARouterUrl.ROUTE_ME_MODULE_LOGIN_ACTIVITY)
                            .navigation()
                    }
                }
            }
            ConstantConfig.STATE_EMPTY_LIST -> {
                mBinding.multiStateContainer.show<EmptyFollowPageState>{
                    it.onClick {
                        //进入首页，explore页面
                        EventBus.getDefault().post(MainPageEvent(0))
                    }
                }
            }
            ConstantConfig.STATE_NETWORK_ERROR -> {
                mBinding.multiStateContainer.show<NetworkErrorState>{
                    it.onRetry {
                        mViewModel.retryLastCall()
                    }
                }
            }
        }
    }

    private val mWatcher = object: UserWatcher.MusicStateWatcher{

        override fun onMusicChanged(music: LocalMediaListItemBean) {
            mCurrentMusic = music
            mAdapter.setCurrentMusic(music)
        }

        override fun onPlayTimeChanged(currentInt: Int, totalInt: Int, current: String, total: String) {}

        override fun onPlayPercentChanged(percent: Int) {}

        override fun onPlayStateChanged(state: Int) {
            mCurrentPlayState = state
            mAdapter.setCurrentPlayState(state)
        }

        override fun onPlaySpeedChanged(speed: Float) {}

        override fun onPlayListChanged() {}
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Kukoo.watcher.register(mWatcher)
    }

    override fun onDestroy() {
        super.onDestroy()
        Kukoo.watcher.unregister(mWatcher)
    }

}